#!/usr/bin/env bash

#set -x

old=false
if [ "$1" = "--old" ]; then
    old=true
    shift
fi

cd $(dirname $0)
CI_DIR=$PWD
cd -
    
while (( "$#" ))
do
    if [ -d $1 ] && [ -e $1/.travis.yml ]; then
        echo "%%%%% Generating CI files for $1"
        echo
        cd $1
        if [ ! -d .ci ]; then
            echo "Didn't find .ci directory. Bailing out!"
            exit
        fi
        if [ -e .ci/.travis.pre ]; then
            cat .ci/.travis.pre > .travis.yml
            echo >> .travis.yml
        else
            echo "No .travis.pre file found. Bailing out!"
            exit
        fi
        if [ $old = true ]; then 
            cat $CI_DIR/.travis.build.old >> .travis.yml
        else
            cat $CI_DIR/.travis.build >> .travis.yml
        fi
#        if [ -e .ci/.travis.post ]; then
#            cat .ci/.travis.post >> .travis.yml
#        fi
        case $1 in
            Clp|Cbc|Dip|SYMPHONY|Blis)
                echo >> .travis.yml
                cat $CI_DIR/.travis.upload >> .travis.yml
                ;;
            *)
                ;;
        esac
        if [ -e .ci/.travis.post ]; then
            eacho "Warning: .travis.post still exists"
        fi
        #git add .travis.yml
        if [ -e .ci/appveyor.pre ]; then
            cat .ci/appveyor.pre > appveyor.yml
            echo >> appveyor.yml
        else
            echo "No appveyor.pre file found. Bailing out!"
            exit
        fi
        if [ $old = true ]; then 
            cat $CI_DIR/appveyor.build.old >> appveyor.yml
        else
            cat $CI_DIR/appveyor.build >> appveyor.yml
        fi
        case $1 in
            Clp|Cbc|Dip|SYMPHONY|Blis)
                echo >> appveyor.yml
                if [ $old = true ]; then 
                    cat $CI_DIR/appveyor.upload.old >> appveyor.yml
                else
                    cat $CI_DIR/appveyor.upload >> appveyor.yml
                fi
                ;;
            *)
                ;;
        esac
        if [ -e .ci/appveyor.post ]; then
            eacho "Warning: appveyor.post still exists"
        fi
        #git add appveyor.yml
        #git commit -m "Updating Travis and Appveyor"
        cd -
    fi
    shift
done
